package com.gongzonqiang.controller.client;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.gongzonqiang.myenum.UserEnum;
import com.gongzonqiang.pojo.Notice;
import com.gongzonqiang.pojo.User;
import com.gongzonqiang.povo.CommentVo;
import com.gongzonqiang.povo.NoticeVo;
import com.gongzonqiang.service.UserService;
import com.gongzonqiang.utils.JsonUtils;
import com.gongzonqiang.utils.ResResult;
import com.gongzonqiang.utils.UserRedisUtil;

/**
 * 用户contro
 * 
 * @author youjie
 *
 */
@RestController
@RequestMapping("/client/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private UserRedisUtil userRedisUtil;

	@Value("${wx.appId}")
	private String appId;
	@Value("${wx.secret}")
	private String secret;

	Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 微信登录
	 */
	@RequestMapping("/login")
	public ResResult login(String code, String nickName, String headImg) throws Exception {

		// 获取openid
		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
				+ "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code", String.class);
		logger.info("[用户登录] oppen: {}", result);
		ObjectMapper mapper = new ObjectMapper();
		// json字符串转为Map对象
		Map map = mapper.readValue(result, Map.class);
		// {"session_key":"MB\/2x2X7ljCE2DqcKSBrqw==","expires_in":7200,"openid":"oIYEY0X0BZp040Y4gzoR4-JkrNGk"}
		if (map.get("errcode") != null) {
			return ResResult.build(400, "登录失败");
		}
		// 判断数据库中是否存在
		User dbuser = userService.selectById((String) map.get("openid"));

		String token = UUID.randomUUID().toString();
		// 没有则保存
		if (dbuser == null) {
			User user = new User();
			user.setOpenid((String) map.get("openid"));
			user.setNickname(nickName);
			user.setHeadimg(headImg);
			user.setStatus(UserEnum.NORMAL_USER.getCode());
			userService.addUser(user);
			dbuser = user;
		}

		// 保存到redis
		redisTemplate.opsForValue().set("user:" + token, JsonUtils.objectToJson(dbuser), 86400, TimeUnit.SECONDS); // 保存1天
		// 有返回
		return ResResult.ok("user:" + token);
	}

	/**
	 * 登录是否过期
	 * 
	 * @param token
	 * @return
	 */
	@RequestMapping("/userIsExpire")
	public ResResult userIsExpire(String token) {
		String userString = redisTemplate.opsForValue().get(token);
		if (userString == null) {
			return new ResResult(300, "身份过期", null);
		}
		return ResResult.ok();
	}

	/**
	 * 用户绑定手机号码
	 * 
	 * @param token
	 * @param phone
	 * @return
	 */
	@RequestMapping("/bindingPhone")
	public ResResult bindingPhone(String token, String phone) {
		User loginUser = userRedisUtil.getUser(token);
		loginUser.setPhone(phone);
		userService.bindingPhone(loginUser);
		
		// 绑定手机号了要更新redis
		redisTemplate.opsForValue().set(token, JsonUtils.objectToJson(loginUser));

		return ResResult.ok();
	}

	/**
	 * 查看我的发布(用户)
	 * 
	 * @param token
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/myRelease")
	public ResResult myRelease(String token, Integer pageNum, Integer pageSize) {
		User loginUser = userRedisUtil.getUser(token);
		PageInfo<NoticeVo> myRelease = userService.MyRelease(pageNum, pageSize, loginUser);
		return ResResult.ok(myRelease);
	}

	/**
	 * 查看我的收藏
	 * 
	 * @param token
	 * @return
	 */
	@RequestMapping("/myCollection")
	public ResResult myCollection(String token) {
		User loginUser = userRedisUtil.getUser(token);
		PageInfo<NoticeVo> myCollection = userService.MyCollection(1, 99999, loginUser);
		return ResResult.ok(myCollection);
	}

	/**
	 * 查看我的评论(用户)
	 * 
	 * @param token
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/myComment")
	public ResResult myComment(String token, Integer pageNum, Integer pageSize) {
		User loginUser = userRedisUtil.getUser(token);
		PageInfo<CommentVo> myComment = userService.MyComment(pageNum, pageSize, loginUser);
		return ResResult.ok(myComment);
	}

	/**
	 * 查看消息通知(我发布的公告被评论了)(用户)
	 * 
	 * @param token
	 * @return
	 */
	@RequestMapping("/messageNotification")
	public ResResult messageNotification(String token) {
		User loginUser = userRedisUtil.getUser(token);
		PageInfo<NoticeVo> messageNotification = userService.messageNotification(1, 99999, loginUser);
		return ResResult.ok(messageNotification);
	}

	/**
	 * 通過用戶id獲取用戶
	 * 
	 * @param token
	 * @return
	 */
	@RequestMapping("/getUserById")
	public User getUserById(String token) {

		return userRedisUtil.getUser(token);
	}
}
